//
//  PlatformTools.m
//  CedarSuperCloud
//
//  Created by lshenrong on 2017/11/24.
//  Copyright © 2017年 cedarhd. All rights reserved.
//

#import "PlatformTools.h"
#include <sys/utsname.h>
#import <SAMKeychain/SAMKeychainQuery.h>
#include <ifaddrs.h>
#include <arpa/inet.h>
#import <UserNotifications/UserNotifications.h>
#import "CedarTabBarController.h"

@implementation PlatformTools

+ (NSString *)appVersion{
    NSDictionary *infoDic = [[NSBundle mainBundle] infoDictionary];
    NSString *currentVersion = [infoDic objectForKey:@"CFBundleShortVersionString"];
    return currentVersion;
}

//+ (NSString *)deviceUDID{
//    NSString *bundleIdentifier = [[NSBundle mainBundle] bundleIdentifier];
//    NSString *service = [NSString stringWithFormat:@"%@.Service",bundleIdentifier];
//    NSString *account = [NSString stringWithFormat:@"%@.cn.com.lingyikeji.account",bundleIdentifier];
//    NSString *openUDID = [SAMKeychain passwordForService:service account:account];
//    if (openUDID == nil || [openUDID isEqualToString:@""]) {
//        openUDID = [OpenUDID value];
//        [SAMKeychain setPassword:openUDID forService:service account:account];
//    }
//    CLog(@"openUDID %@",openUDID);
//    return openUDID;
//}

+ (NSString *)getBundleID{
    return [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleIdentifier"];
}


+ (NSString *)deviceTokenString:(NSData *)data{
    NSString *deviceToken = [[[data description] stringByReplacingOccurrencesOfString:@"<"withString:@""]
                                     stringByReplacingOccurrencesOfString:@">" withString:@""];
    return deviceToken;
}



+ (NSString *)deviceModel{
    struct utsname systemInfo;
    uname(&systemInfo);
    NSString *deviceString = [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
    
    //--------------------iphone-----------------------
    if ([deviceString isEqualToString:@"i386"] || [deviceString isEqualToString:@"x86_64"])    return @"iPhone Simulator";
    if ([deviceString isEqualToString:@"iPhone1,1"])    return @"iPhone 2G";
    if ([deviceString isEqualToString:@"iPhone1,2"])    return @"iPhone 3G";
    if ([deviceString isEqualToString:@"iPhone2,1"])    return @"iPhone 3GS";
    if ([deviceString isEqualToString:@"iPhone3,1"] || [deviceString isEqualToString:@"iPhone3,2"] || [deviceString isEqualToString:@"iPhone3,3"])    return @"iPhone 4";
    if ([deviceString isEqualToString:@"iPhone4,1"])    return @"iPhone 4S";
    if ([deviceString isEqualToString:@"iPhone5,1"] || [deviceString isEqualToString:@"iPhone5,2"])    return @"iPhone 5";
    if ([deviceString isEqualToString:@"iPhone5,3"] || [deviceString isEqualToString:@"iPhone5,4"])    return @"iPhone 5c";
    if ([deviceString isEqualToString:@"iPhone6,1"] || [deviceString isEqualToString:@"iPhone6,2"])    return @"iPhone 5s";
    
    if ([deviceString isEqualToString:@"iPhone7,1"])    return @"iphone 6 Plus";
    if ([deviceString isEqualToString:@"iPhone7,2"])    return @"iphone 6";
    if ([deviceString isEqualToString:@"iPhone8,1"])    return @"iPhone 6s";
    if ([deviceString isEqualToString:@"iPhone8,2"])    return @"iPhone 6s Plus";
    if ([deviceString isEqualToString:@"iPhone8,4"])    return @"iPhone SE";
    
    if ([deviceString isEqualToString:@"iPhone9,1"] || [deviceString isEqualToString:@"iPhone9,3"])    return @"iPhone 7";
    if ([deviceString isEqualToString:@"iPhone9,2"] || [deviceString isEqualToString:@"iPhone9,4"])    return @"iPhone 7 Plus";
    if ([deviceString isEqualToString:@"iPhone10,1"] || [deviceString isEqualToString:@"iPhone10,4"])    return @"iPhone 8";
    if ([deviceString isEqualToString:@"iPhone10,2"] || [deviceString isEqualToString:@"iPhone10,5"])    return @"iPhone 8 Plus";
    if ([deviceString isEqualToString:@"iPhone10,3"] || [deviceString isEqualToString:@"iPhone10,6"])    return @"iPhone X";
    
    if ([deviceString isEqualToString:@"iPhone11,2"])    return @"iPhone XS";
    if ([deviceString isEqualToString:@"iPhone11,8"])    return @"iPhone XR";
    if ([deviceString isEqualToString:@"iPhone11,4"] || [deviceString isEqualToString:@"iPhone11,6"])    return @"iPhone XS Max";
 
    //--------------------ipod-----------------------
    if ([deviceString isEqualToString:@"iPod1,1"])    return @"iPod touch";
    if ([deviceString isEqualToString:@"iPod2,1"])    return @"iPod touch 2G";
    if ([deviceString isEqualToString:@"iPod3,1"])    return @"iPod touch 3G";
    if ([deviceString isEqualToString:@"iPod4,1"])    return @"iPod touch 4G";
    if ([deviceString isEqualToString:@"iPod5,1"])    return @"iPod touch 5G";
    if ([deviceString isEqualToString:@"iPod7,1"])    return @"iPod touch 6G";
    
    
    //--------------------ipad-------------------------
    if ([deviceString isEqualToString:@"iPad1,1"])    return @"iPad";
    if ([deviceString isEqualToString:@"iPad2,1"] || [deviceString isEqualToString:@"iPad2,2"] || [deviceString isEqualToString:@"iPad2,3"] || [deviceString isEqualToString:@"iPad2,4"])    return @"iPad 2";
    
    if ([deviceString isEqualToString:@"iPad3,1"] || [deviceString isEqualToString:@"iPad3,2"] || [deviceString isEqualToString:@"iPad3,3"])    return @"iPad 3";
    if ([deviceString isEqualToString:@"iPad3,4"] || [deviceString isEqualToString:@"iPad3,5"] || [deviceString isEqualToString:@"iPad3,6"])    return @"iPad 4";
    if ([deviceString isEqualToString:@"iPad4,1"] || [deviceString isEqualToString:@"iPad4,2"] || [deviceString isEqualToString:@"iPad4,3"])    return @"iPad Air";
    if ([deviceString isEqualToString:@"iPad5,3"] || [deviceString isEqualToString:@"iPad5,4"])    return @"iPad Air 2";
    if ([deviceString isEqualToString:@"iPad6,7"] || [deviceString isEqualToString:@"iPad6,8"])    return @"iPad Pro 12.9-inch";
    if ([deviceString isEqualToString:@"iPad6,3"] || [deviceString isEqualToString:@"iPad6,4"])    return @"iPad Pro iPad 9.7-inch";
    if ([deviceString isEqualToString:@"iPad6,11"] || [deviceString isEqualToString:@"iPad6,12"])    return @"iPad 5";
    if ([deviceString isEqualToString:@"iPad7,1"] || [deviceString isEqualToString:@"iPad7,2"])    return @"iPad Pro 12.9-inch 2";
    if ([deviceString isEqualToString:@"iPad7,3"] || [deviceString isEqualToString:@"iPad7,4"])    return @"iPad Pro 10.5-inch";
    
    //----------------iPad mini------------------------
    if ([deviceString isEqualToString:@"iPad2,5"] || [deviceString isEqualToString:@"iPad2,6"] || [deviceString isEqualToString:@"iPad2,7"])    return @"iPad mini";
    if ([deviceString isEqualToString:@"iPad4,4"] || [deviceString isEqualToString:@"iPad4,5"] || [deviceString isEqualToString:@"iPad4,6"])    return @"iPad mini 2";
    if ([deviceString isEqualToString:@"iPad4,7"] || [deviceString isEqualToString:@"iPad4,8"] || [deviceString isEqualToString:@"iPad4,9"])    return @"iPad mini 3";
    if ([deviceString isEqualToString:@"iPad5,1"] || [deviceString isEqualToString:@"iPad5,2"])    return @"iPad mini 4";
    
    if ([deviceString isEqualToString:@"iPad4,1"])    return @"ipad air";
    
    return deviceString;
}

+ (void)makeCallWithNumber:(NSString *)phoneNumber{
    if (!IsEmptyStr(phoneNumber)) {
        NSString *num = [[NSString alloc] initWithFormat:@"telprompt://%@",phoneNumber];
        if (@available(iOS 10.0, *)) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:num] options:@{UIApplicationOpenURLOptionUniversalLinksOnly: @NO} completionHandler:nil ];
        } else {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:num]];
        }
    }
}

+ (NSString *)deviceGUID{
    CFUUIDRef theUUID =CFUUIDCreate(NULL);
    CFStringRef guid = CFUUIDCreateString(NULL, theUUID);
    CFRelease(theUUID);
   // NSString *uuidString = [((__bridge NSString *)guid)stringByReplacingOccurrencesOfString:@"-"withString:@""];
    NSString *uuidString = (__bridge NSString *)guid;
    CFRelease(guid);
    return uuidString;
}

+ (NSString *)appName{
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *app_Name = [infoDictionary objectForKey:@"CFBundleDisplayName"];
    return app_Name;
}

+ (NSString*)getCurrentTime{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    NSDate *datenow = [NSDate date];
    NSString *currentTimeString = [formatter stringFromDate:datenow];
    return currentTimeString;
}

+ (NSTimeInterval)dateTimeDifferenceWithStartTime:(NSString *)startTime endTime:(NSString *)endTime{
    NSDateFormatter *date = [[NSDateFormatter alloc]init];
    [date setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *startD =[date dateFromString:startTime];
    NSDate *endD = [date dateFromString:endTime];
    NSTimeInterval start = [startD timeIntervalSince1970]*1;
    NSTimeInterval end = [endD timeIntervalSince1970]*1;
    NSTimeInterval value = end - start;//秒
    return value;
}

//750 1334为参考
+ (CGFloat)fontSizeAdaptation:(CGFloat)fontsize{
    return SCREEN_WIDTH*fontsize/750;
}

+ (CGFloat)heightAdaptation:(CGFloat)height{
    return SCREEN_WIDTH*height/750; //375X667
}

+ (CGFloat)WidthAdaptationForAuth:(CGFloat)width{
    return SCREEN_WIDTH*750/570;
}

+ (CGFloat)adaptationByScreenWidthAt375:(CGFloat)value{
    CGFloat newValue = SCREEN_WIDTH*value/375;
    return newValue;
}


+ (UIBarButtonItem *)barButtonItemWithTitle:(NSString *)titlte target:(id)target  action:(SEL)action{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setTitle:titlte forState:UIControlStateNormal];
    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [button setTitleColor:[UIColor grayColor] forState:UIControlStateHighlighted];
    //button.titleLabel.font = [UIFont systemFontOfSize:15.0];
    [button addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *item =  [[UIBarButtonItem alloc]initWithCustomView:button];
    return item;
}
//
//+ (CGFloat)tabbarHeight{
//    CGRect frame  = kUtilsAppDelegate.tabbarFrame;
//    if (frame.size.height>0) {
//        return frame.size.height;
//    }
//    if(IsPhoneX){
//        return 83.0;
//    }
//    return 49.0;
//}

+ (NSString *)deviceIPAdress {
    NSString *address = @"an error occurred when obtaining ip address";
    struct ifaddrs *interfaces = NULL;
    struct ifaddrs *temp_addr = NULL;
    int success = 0;
    success = getifaddrs(&interfaces);
    if (success == 0) { // 0 表示获取成功
        temp_addr = interfaces;
        while (temp_addr != NULL) {
            if( temp_addr->ifa_addr->sa_family == AF_INET) {
                // Check if interface is en0 which is the wifi connection on the iPhone
                if ([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
                    // Get NSString from C String
                    address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
                }
            }
            temp_addr = temp_addr->ifa_next;
        }
    }
    freeifaddrs(interfaces);
    return address;
}


+ (NSString *)dataCachePath:(NSString *)name{
    NSString *cacheFolder = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
    NSString *path = [cacheFolder stringByAppendingPathComponent:name];
    return path;
}


#pragma mark - controller

+ (UIViewController *)getCurrentViewController{
    AppDelegate *appdelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    UIViewController *rootViewController = appdelegate.window.rootViewController;
    UIViewController *currentVC = [self getCurrentVCFrom:rootViewController];
    return currentVC;
}

+ (UIViewController *)getCurrentVCFrom:(UIViewController *)rootVC{
    UIViewController *currentVC;
    if ([rootVC presentedViewController]) {
        rootVC = [rootVC presentedViewController];
    }
    
    if ([rootVC isKindOfClass:[UITabBarController class]]) {
        currentVC = [self getCurrentVCFrom:[(UITabBarController *)rootVC selectedViewController]];
    } else if ([rootVC isKindOfClass:[UINavigationController class]]){
        currentVC = [self getCurrentVCFrom:[(UINavigationController *)rootVC visibleViewController]];
    } else {
        // 根视图为非导航类
        currentVC = rootVC;
    }
    return currentVC;
}


+ (UINavigationController *)currentNavigationController{
    UIViewController *vc =  [self getCurrentViewController];
    return vc.navigationController;
}

+ (UINavigationController *)theRootNavigationController{
    AppDelegate *appdelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    UIViewController *rootViewController = appdelegate.window.rootViewController;
    UINavigationController *navigationVC = nil;
    if([rootViewController isKindOfClass:[CedarTabBarController class]]){
        CedarTabBarController *tabController = (CedarTabBarController *)rootViewController;
        if ([tabController.childViewControllers count]>0) {
            navigationVC = tabController.childViewControllers[tabController.selectedIndex];//首页
        }
    }else if([rootViewController isKindOfClass:[UINavigationController class]]){
        navigationVC = (UINavigationController *)rootViewController;
    }
    return navigationVC;
}

+ (CGSize)sizeWithString:(NSString *)str andFount:(UIFont *)font andMaxSize:(CGSize)size{
    NSDictionary *attrs = @{NSFontAttributeName : font};
    return [str boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil].size;
}

+ (void)openSystemBrowserWithURL:(NSString *)url{
    if (@available(iOS 10.0, *)) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url] options:@{UIApplicationOpenURLOptionUniversalLinksOnly: @NO} completionHandler:^(BOOL success) {
            
        } ];
    }else{
         [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
    }
}

+ (UIImage *)screenCaptureFromScrollView:(UIScrollView *)view{
    if (!view) {
        return nil;
    }
    view.frame = view.superview.frame;
    CGRect sourceFrame = view.frame;
    CGRect frm = view.frame;
    frm.size.height = view.contentSize.height;
    view.frame = frm;
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(view.frame.size.width,view.frame.size.height), YES, 0);     //设置截屏大小
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    CGImageRef imageRef = viewImage.CGImage;
    UIImage *sendImage = [[UIImage alloc] initWithCGImage:imageRef];
    view.frame = sourceFrame;
    return sendImage;
}

+ (UIWindow *)currentKeyWindow{
    UIWindow *window = nil;
    id<UIApplicationDelegate> delegate = [[UIApplication sharedApplication] delegate];
    if ([delegate respondsToSelector:@selector(window)]) {
        window = [delegate performSelector:@selector(window)];
    } else {
        window = [[UIApplication sharedApplication] keyWindow];
    }
    return window;
}

+ (BOOL)isSpecificScreen{
    CGSize size = [[UIScreen mainScreen] currentMode].size;
    if(CGSizeEqualToSize(CGSizeMake(1125, 2436),size)  || CGSizeEqualToSize(CGSizeMake(750, 1624),size) ){
        return YES;
    }
    return NO;
}




+ (UIImage*)getGrayImage:(UIImage*)sourceImage{
    CGFloat width = sourceImage.size.width;
    CGFloat height = sourceImage.size.height;
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();
    CGContextRef context = CGBitmapContextCreate (nil,width,height,8,0,colorSpace,kCGImageAlphaNone);
    CGColorSpaceRelease(colorSpace);
    if (context == NULL) {
        return nil;
    }
    CGContextDrawImage(context,CGRectMake(0, 0, width, height), sourceImage.CGImage);
    CGImageRef grayImageRef = CGBitmapContextCreateImage(context);
    UIImage *grayImage = [UIImage imageWithCGImage:grayImageRef];
    CGContextRelease(context);
    CGImageRelease(grayImageRef);
    return grayImage;
}




+ (YearMonth *)currentYearMonth{
    NSCalendar *cal = [NSCalendar currentCalendar];
    NSDateComponents *components = [cal components:(NSCalendarUnitYear|NSCalendarUnitMonth) fromDate:[NSDate date]];
    YearMonth *yeahMonth = [[YearMonth alloc]init];
    yeahMonth.year = components.year;
    yeahMonth.month = components.month;
    NSDate *newDate = [cal dateFromComponents:components];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyy年MM月";
    yeahMonth.dateStr =  [formatter stringFromDate:newDate];
    return yeahMonth;
}

+ (NSArray<YearMonth *> *)MonthAtCurrent:(NSArray *)offsetArray{
    if(!offsetArray){
        return nil;
    }
    NSMutableArray *mMonth =  [NSMutableArray array];
    // NSCalendar *calendar = [NSCalendar currentCalendar];
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDate *date = [NSDate date];
    //NSArray *offsetArray = @[@(0),@(-1),@(-2),@(-3)];
    NSInteger unitFlags = NSCalendarUnitYear|NSCalendarUnitMonth;
    for (NSInteger i = 0; i<[offsetArray count]; i++) {
        NSNumber *number = offsetArray[i];
        NSInteger value = number.integerValue;
        NSDateComponents *components = [calendar components:unitFlags fromDate:date];
        [components setMonth:components.month + value];
        YearMonth *yeahMonth = [[YearMonth alloc]init];
        NSDate *newDate = [calendar dateFromComponents:components];
        NSDateComponents *newComps = [[NSDateComponents alloc] init];
        NSCalendar *newCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
        newComps = [newCalendar components:unitFlags fromDate:newDate];
        
        yeahMonth.year = newComps.year;
        yeahMonth.month = newComps.month;
        yeahMonth.dateStr =  [NSString stringWithFormat:@"%ld年%ld月",yeahMonth.year,yeahMonth.month];
        [mMonth addObject:yeahMonth];
    }
    return mMonth;
}


+ (NSArray<YearMonth *> *)monthAtCurrentForTransactionRecord{
    NSMutableArray *mMonth =  [NSMutableArray array];
    for (NSInteger i = 0; i<3; i++) {
        YearMonth *yeahMonth = [[YearMonth alloc]init];
        if(i== 0){
             yeahMonth.month = 1;
        }else if(i== 1){
             yeahMonth.month = 3;
        }else if(i== 2){
            yeahMonth.month = 6;
        }
        if(i == 2){
            yeahMonth.dateStr = @"最近半年";
        }else{
            yeahMonth.dateStr =  [NSString stringWithFormat:@"最近%ld个月",yeahMonth.month];
        }
        [mMonth addObject:yeahMonth];
    }
    return mMonth;
}



+ (void)getPushNotificationSettingBlock:(PushNotificationSetting)returnBlock{
    if (@available(iOS 10.0, *)){
        [[UNUserNotificationCenter currentNotificationCenter] getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings *settings) {
            if(returnBlock){
                returnBlock(settings.authorizationStatus == UNAuthorizationStatusAuthorized);
            }
        }];
    }else{
        UIUserNotificationSettings *setting = [[UIApplication sharedApplication] currentUserNotificationSettings];
        if(returnBlock){
            returnBlock(setting.types != UIUserNotificationTypeNone);
        }
    }
}


//遍历获取指定类型的属性,替代就有的私有属性获取

+ (UIView *)FindSpecifiedSubViewFromClassName:(NSString *)className inView:(UIView *)superView {
    Class specificView = NSClassFromString(className);
       if ([superView isKindOfClass:specificView]) {
           return superView;
       }

       if (superView.subviews.count > 0) {
           for (UIView *subView in superView.subviews) {
               UIView *targetView = [self FindSpecifiedSubViewFromClassName:className inView:subView];
               if (targetView != nil) {
                   return targetView;
               }
           }
       }
       
       return nil;
}



@end

@implementation YearMonth

- (NSString *)timeFormateString{
    if([self.dateStr isEqualToString:@"全部"]){
        return nil;
    }
    NSString *str = [NSString stringWithFormat:@"%ld-%02ld-01",(long)self.year,(long)self.month];
    return str;
}


@end
